/*
// 用户行为监控控制器 - 已注释
// 如需重新启用，请取消注释

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Lzfy_Refund_Service.Services;
using Lzfy_Refund_Service.Models;
using System.Security.Claims;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class UserBehaviorController : ControllerBase
    {
        private readonly IUserBehaviorService _behaviorService;
        private readonly ILogger<UserBehaviorController> _logger;

        public UserBehaviorController(IUserBehaviorService behaviorService, ILogger<UserBehaviorController> logger)
        {
            _behaviorService = behaviorService;
            _logger = logger;
        }

        /// <summary>
        /// 跟踪用户行为
        /// </summary>
        [HttpPost("track")]
        public async Task<IActionResult> TrackUserAction([FromBody] BehaviorTrackingRequest request)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized("用户未认证");
                }

                var userAgent = Request.Headers["User-Agent"].ToString();
                var ipAddress = GetClientIpAddress();

                var success = await _behaviorService.TrackUserActionAsync(request, userId, userAgent, ipAddress);
                
                if (success)
                {
                    return Ok(new { success = true, message = "行为跟踪成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "行为跟踪失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "跟踪用户行为失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 开始操作会话
        /// </summary>
        [HttpPost("session/start")]
        public async Task<IActionResult> StartOperationSession([FromBody] StartSessionRequest request)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized("用户未认证");
                }

                var session = await _behaviorService.StartOperationSessionAsync(
                    request.SessionId, userId, request.TaskDetailId, request.PatientId, 
                    request.PatientName, request.PhoneNumber);

                if (session != null)
                {
                    return Ok(new { success = true, sessionId = session.SessionId, message = "会话开始成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "会话开始失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始操作会话失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 完成操作会话
        /// </summary>
        [HttpPost("session/complete")]
        public async Task<IActionResult> CompleteOperationSession([FromBody] CompleteSessionRequest request)
        {
            try
            {
                var success = await _behaviorService.CompleteOperationSessionAsync(
                    request.SessionId, request.ContactResult, request.UserNotes);

                if (success)
                {
                    return Ok(new { success = true, message = "会话完成成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "会话完成失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "完成操作会话失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 分析会话风险
        /// </summary>
        [HttpGet("session/{sessionId}/analyze")]
        public async Task<IActionResult> AnalyzeSession(string sessionId)
        {
            try
            {
                var result = await _behaviorService.AnalyzeSessionAsync(sessionId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析会话失败: {SessionId}", sessionId);
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 获取可疑操作列表
        /// </summary>
        [HttpGet("suspicious")]
        [Authorize(Roles = "Admin,Manager")] // 只有管理员可以查看
        public async Task<IActionResult> GetSuspiciousOperations([FromQuery] decimal minRiskScore = 5.0m)
        {
            try
            {
                var operations = await _behaviorService.GetSuspiciousOperationsAsync(minRiskScore);
                return Ok(operations);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取可疑操作失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 获取用户每日统计
        /// </summary>
        [HttpGet("statistics/daily")]
        public async Task<IActionResult> GetUserDailyStatistics([FromQuery] DateTime? date = null)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized("用户未认证");
                }

                var targetDate = date ?? DateTime.Today;
                var statistics = await _behaviorService.GetUserDailyStatisticsAsync(userId, targetDate);
                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户每日统计失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 更新用户每日统计
        /// </summary>
        [HttpPost("statistics/daily/update")]
        public async Task<IActionResult> UpdateUserDailyStatistics([FromQuery] DateTime? date = null)
        {
            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized("用户未认证");
                }

                var targetDate = date ?? DateTime.Today;
                var success = await _behaviorService.UpdateDailyStatisticsAsync(userId, targetDate);
                
                if (success)
                {
                    return Ok(new { success = true, message = "统计更新成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "统计更新失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新用户每日统计失败");
                return StatusCode(500, new { success = false, message = "服务器内部错误" });
            }
        }

        private string GetClientIpAddress()
        {
            var ipAddress = Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = Request.Headers["X-Real-IP"].FirstOrDefault();
            }
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
            }
            return ipAddress ?? "Unknown";
        }
    }

    // 请求模型
    public class StartSessionRequest
    {
        public string SessionId { get; set; } = string.Empty;
        public long TaskDetailId { get; set; }
        public string PatientId { get; set; } = string.Empty;
        public string? PatientName { get; set; }
        public string? PhoneNumber { get; set; }
    }

    public class CompleteSessionRequest
    {
        public string SessionId { get; set; } = string.Empty;
        public string ContactResult { get; set; } = string.Empty;
        public string? UserNotes { get; set; }
    }
}
*/